JSP 購物車的範例
1.建立一個DummyCart的物件來儲存所選的項目
2.把已經選擇的物品列到最上面,並include一個下拉式選單
3.把可以選擇的物品用下拉式選單列出
建立一個DummyCart的物件來儲存所選的項目
=== DummyCart.java ===
package sessions;
import java.util.Vector;
public class DummyCart {
    Vector<String> v = new Vector<String>();
    String submit = null;
    String item = null;
    
    private void addItem(String name) {
        v.addElement(name);
    }
    private void removeItem(String name) {
        v.removeElement(name);
    }
    public void setItem(String name) {
        item = name;
    }
    
    public void setSubmit(String s) {
        submit = s;
    }
    public String[] getItems() {
        String[] s = new String[v.size()];
        v.copyInto(s);
        return s;
    }
    
    public void processRequest() {
        // null value for submit - user hit enter instead of clicking on 
        // "add" or "remove"
        if (submit == null || submit.equals("add"))
            addItem(item);
        else if (submit.equals("remove")) 
            removeItem(item);
        
        // reset at the end of the request
        reset();
    }
    // reset
    private void reset() {
        submit = null;
        item = null;
    }
}
把已經選擇的物品列到最上面,並include一個下拉式選單
=== cart.jsp ===
<jsp:useBean id="cart" scope="session" class="sessions.DummyCart" />
<jsp:setProperty name="cart" property="*" />
<%
	cart.processRequest();
%>
<FONT size = 5 COLOR="#CC0000">
<br> You have the following items in your cart:
<ol>
<% 
	String[] items = cart.getItems();
	for (int i=0; i<items.length; i++) {
%>
<li> <% out.print(util.HTMLFilter.filter(items[i])); %> 
<%
	}
%>
</ol>
</FONT>
<hr>
<%@ include file ="carts.html" %>
把可以選擇的物品用下拉式選單列出
=== carts.html ===
    <title>carts</title>
 <body bgcolor="white">
<font size = 5 color="#CC0000">
<form type=POST action=carts.jsp>
<BR>
Please enter item to add or remove:
<br>
Add Item:
<SELECT NAME="item">
<OPTION>Beavis & Butt-head Video collection
<OPTION>X-files movie
<OPTION>Twin peaks tapes
<OPTION>NIN CD
<OPTION>JSP Book
<OPTION>Concert tickets
<OPTION>Love life
<OPTION>Switch blade
<OPTION>Rex, Rugs & Rock n' Roll
</SELECT>
<br> <br>
<INPUT TYPE=submit name="submit" value="add">
<INPUT TYPE=submit name="submit" value="remove">
</form>
</FONT>